package 牛客_面试必刷.Month07.day12;

import java.util.ArrayList;
import java.util.Arrays;

public class 三数之和 {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {
            //前面的这两个都还挺重要的
            if(num[i] > 0) break;
            //这里要注意写法哈
            if(i > 0 && num[i] == num[i - 1]){
                continue;
            }
            int left = i + 1;
            int right = num.length - 1;
            while(left < right){
                int target = num[i] + num[left] + num[right];
                if(target > 0){
                    right--;
                }else if(target < 0){
                    left++;
                }else{
                    ArrayList<Integer> list = new ArrayList();
                    list.add(num[i]);
                    list.add(num[left]);
                    list.add(num[right]);
                    lists.add(list);

                    while(left < right && num[left] == num[left + 1]){
                        left++;
                    }

                    while(left < right && num[right] == num[right - 1]){
                        right--;
                    }
                    left++;
                    right--;
                }
            }
        }
        return lists;
    }
}
